﻿/*

The MIT License

Copyright (c) 2010 Cartesian Analytics, Inc. 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

using System;
using Pipra.Math;
using Pipra.Math.Geometry;

namespace Pipra.Gis.Projection
{
    /// <summary>
    /// A mercator projection, 1SP or 2SP.
    /// </summary>
    public class Mercator : ProjectionBase
    {

        protected readonly double CentralMeridian;

        protected readonly double Ak;
        protected readonly double LatLineCoef1;
        protected readonly double LatLineCoef2;
        protected readonly double LatLineCoef3;
        protected readonly double LatLineCoef4;

        private readonly string _name;

        private class Inverted : InvertedProjectionBase<Mercator>
        {

            public Inverted(Mercator core) : base(core)
            {
                if(0 == Core.Ak)
                {
                    throw new ArgumentException("Core cannot be inverted.");
                }
            }

            public override LatLon TransformValue(Point2 coord)
            {
                double x = HalfPi - (
                    2.0 * System.Math.Atan(
                        System.Math.Pow(
                            System.Math.E,
                            (Core.FalseProjectedOffset.Y - coord.Y) / Core.Ak
                        )
                    )
                );
                return new LatLon(
                    (
                        x
                        + (Core.LatLineCoef1 * System.Math.Sin(2.0 * x))
                        + (Core.LatLineCoef2 * System.Math.Sin(4.0 * x))
                        + (Core.LatLineCoef3 * System.Math.Sin(6.0 * x))
                        + (Core.LatLineCoef4 * System.Math.Sin(8.0 * x))
                    ),
                    ((coord.X - Core.FalseProjectedOffset.X) / Core.Ak) + Core.CentralMeridian
                );
            }

        }

        /// <summary>
        /// Constructs a mecator projection from 2 standard parallels.
        /// </summary>
        /// <param name="geographicOrigin">The geographic origin.</param>
        /// <param name="falseProjectedOffset">The flase projected offset.</param>
        /// <param name="spheroid">The speroid.</param>
        public Mercator(
            LatLon geographicOrigin,
            ICoordinatePair<double> falseProjectedOffset,
            ISpheroid<double> spheroid
        )
            : this(
              geographicOrigin.Lon,
              (
                  System.Math.Cos(geographicOrigin.Lat)
                  /
                  System.Math.Sqrt(
                      1.0
                      - (
                          spheroid.ESquared
                          * System.Math.Sin(geographicOrigin.Lat)
                          * System.Math.Sin(geographicOrigin.Lat)
                      )
                  )
              ),
              falseProjectedOffset,
              spheroid
                )
        {
            _name = "Mercator 2SP";
        }

        /// <summary>
        /// Constructs a mercator projection from 1 standard paralell.
        /// </summary>
        /// <param name="centralMeridian">The central meridian.</param>
        /// <param name="scaleFactor">The scale factor.</param>
        /// <param name="falseProjectedOffset">The flase projected offset.</param>
        /// <param name="spheroid">The speroid.</param>
        public Mercator(
            double centralMeridian,
            double scaleFactor,
            ICoordinatePair<double> falseProjectedOffset,
            ISpheroid<double> spheroid
        )
            : base(falseProjectedOffset, spheroid)
        {
            CentralMeridian = centralMeridian;
            Ak = MajorAxis * scaleFactor;
            double e4 = ESq * ESq;
            double e6 = e4 * ESq;
            double e8 = e6 * ESq;
            LatLineCoef1 = (ESq / 2.0) + (5 / 24.0 * e4) + (e6 / 12.0) + (13.0 / 360.0 * e8);
            LatLineCoef2 = (7.0 / 48.0 * e4) + (29.0 / 240.0 * e6) + (811.0 / 11520.0 * e8);
            LatLineCoef3 = (7.0 / 120.0 * e6) + (81.0 / 1120.0 * e8);
            LatLineCoef4 = (4279 / 161280.0 * e8);
            _name = "Mercator 1SP";
        }

        public override Point2 TransformValue(LatLon coord)
        {
            double eSinLat = E * System.Math.Sin(coord.Lat);
            return new Point2(
                FalseProjectedOffset.X + (Ak * (coord.Lon - CentralMeridian)),
                FalseProjectedOffset.Y + (Ak * System.Math.Log(
                    System.Math.Tan(QuarterPi + (coord.Lat / 2.0))
                    *
                    System.Math.Pow((1.0 - eSinLat) / (1.0 + eSinLat), EHalf)
                ))
            );
        }

        public override ITransformation<Point2, LatLon> GetInverse()
        {
            return new Inverted(this);
        }

        public override bool HasInverse
        {
            get { return 0 != Ak; }
        }

        public override string Name
        {
            get { return _name; }
        }

    }
}
